#include "StdAfx.h"
#include "MusicEngine.h"

MusicEngine::MusicEngine()
{
	m_Mobj = NULL;
	m_Output = NULL;
	current = 0;
	tickIn = 500;
}

MusicEngine::~MusicEngine()
{
	delete m_Mobj;
	delete m_Output;
}

void MusicEngine::Init()
{
	m_Mobj = new Phonon::MediaObject;
	m_Output = new Phonon::AudioOutput(Phonon::MusicCategory);
	Phonon::createPath(m_Mobj,m_Output);
	m_Mobj->setTickInterval(tickIn);
	connect(m_Mobj, SIGNAL(tick(qint64)),this, SLOT(CurrentTime(qint64)));
	connect(m_Mobj, SIGNAL(metaDataChanged()),this, SLOT(DataChange()));
	connect(m_Mobj, SIGNAL(finished()), this, SLOT(Finish()));
}
void MusicEngine::Play()
{
//	if(m_slist.empty()) return;          no use
//	m_Mobj->setCurrentSource(SRC(m_slist.at(current)));   no use
	emit beforeplay();
	m_Mobj->play();
}
void MusicEngine::Pause()
{
	emit beforepause();
	m_Mobj->pause();
}
void MusicEngine::Pre()    // no use
{
	if(m_slist.empty()) return;
	if(current == 0)
	{
		return;
	}
	else
	{
		m_Mobj->setCurrentSource(SRC(m_slist.at(--current)));
		Play();
	}
}
void MusicEngine::Next()   // no use
{
	if(m_slist.empty()) return;
	if(current == m_slist.size()-1)
	{
		return;
	}
	else
	{
		m_Mobj->setCurrentSource(SRC(m_slist.at(++current)));
		Play();
	}
}

void MusicEngine::setSongPos(qint64 time_ms)
{
	//if(m_slist.empty()) return;   no use
	m_Mobj->seek(time_ms);
}

void MusicEngine::SetTickIn(qint64 time_ms)
{
	tickIn = time_ms;
	m_Mobj->setTickInterval(tickIn);
}

qint64 MusicEngine::GetTickIn()
{
	return tickIn;
}

void MusicEngine::DataChange()
{
	if ( m_Mobj->currentSource().type() == Phonon::MediaSource::Invalid ||
		m_Mobj->currentSource().type() == Phonon::MediaSource::Empty )
	{
		emit fileInfo(QMultiMap<QString,QString>(),false);
		return;
	}
	m_fileInfo = m_Mobj->metaData();
	emit fileInfo(m_fileInfo,true);
}

void MusicEngine::CurrentTime(qint64 time_ms)
{
	emit currenttime(time_ms);
}

QMultiMap<QString,QString> MusicEngine::Data()
{
	return m_fileInfo;
}

QString MusicEngine::Data(QString &key)
{
	return m_fileInfo.value(key);
}

void MusicEngine::setSRC(SRC src)
{
	m_Mobj->setCurrentSource(src);
}

qint64 MusicEngine::getTotalTime()
{
	return m_Mobj->totalTime();
}

void MusicEngine::SetCurrentIndex(int index)
{
	current = index;
}

void MusicEngine::Finish()
{
	emit Finished();
}
void MusicEngine::setVolume(float vol)
{
	m_Output->setVolume(vol);
}
float MusicEngine::Volume()
{
	return m_Output->volume();
}